package com.example.springbott.config;

import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.LinkedHashMap;

/**
 * @author 1784549954@qq.com
 * @since 2022/11/21 15:01
 */
@Configuration
public class ShiroConfig {
    //ShiroFilter
    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //提供FilterChain
        //filter是谁👉anon、authc、perms
        //Filter作用范围 建立请求和映射关系，顺序为书写顺序
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        //key请求url，value Filter名称
        map.put("/admin/auth/login", "anon");
        map.put("/admin/auth/info","anon");
        map.put("/admin/**", "authc");
        map.put("/wx/home/index","anon");
        map.put("/wx/goods/count","anon");
        map.put("/wx/goods/category","anon");
        map.put("/wx/auth/login","anon");
        map.put("/wx/goods/list","anon");
        map.put("/wx/cart/**","anon");
        map.put("/wx/order/**","authc");

        shiroFilterFactoryBean.setLoginUrl("/admin/auth/login");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map );
        return shiroFilterFactoryBean;
    }

    //SecurityManage
    @Bean
    public DefaultWebSecurityManager securityManager(AuthorizingRealm realm,
                                                     DefaultWebSessionManager sessionManager) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealms(Arrays.asList(realm));
        defaultWebSecurityManager.setSessionManager(sessionManager);
        return defaultWebSecurityManager;
    }

    //可有可无认证器和授权器 Authenticator Authorizer
    //上边两个有默认值


    //Realms 要继承AuthorizingRealm自家写的类可以直接使用Compoent注解注册

//    @Bean
//    public AuthorizingRealm realm(){
//        return new CustomRealm();
//    }


    //SessionManage

    @Bean
    public DefaultWebSessionManager sessionManager() {

        return new MarketSessionManager();
    }
}
